package net.jcip.chapter3;

import net.jcip.annotations.*;

import java.util.Scanner;

/**
 * SynchronizedInteger
 * <p/>
 * Thread-safe mutable integer holder
 * todo 不知道怎么验证
 * @author Brian Goetz and Tim Peierls
 */
@ThreadSafe
class SynchronizedInteger {

    @GuardedBy("this")
    private  int value;

    public synchronized int get() {
        return value;
    }

    public synchronized void set(int value) {
        this.value = value;
    }


    public static void main(String[] args) throws InterruptedException {

        SynchronizedInteger obj = new SynchronizedInteger();

        Thread setThread = new Thread(() -> {

            for (int i = 0; i < 100; i++) {
                // int j = new Random().nextInt(1000);
                System.out.println("INFO  " + Thread.currentThread().getName() + "  value set ==>  " + i);
                obj.set(i);
            }

        }, "设置线程");

        setThread.start();
        //setThread.join(1000);

//        Thread.sleep(1000);
        Thread getThread = new Thread(() -> {

            System.out.println("WARN  " + Thread.currentThread().getName() + "  value get ==>  " + obj.get());


        }, "获取线程");
        getThread.start();


        System.out.println("任意键退出....");
        Scanner scanner = new Scanner(System.in);
        scanner.nextLine();

    }
}
